<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2019/1/15
 * Time: 23:05
 */
namespace app\common\library;


use app\common\model\User;
use app\common\validate\UserValidate;
use fast\Random;
use MongoDB\BSON\ObjectID;
use think\Db;
use think\exception\ValidateException;

class CreateUser
{

    static $userObj = null;
    static $auth = null;
    private static $new; //申请一个私有的静态成员变量来保存该类的唯一实例
    private function __construct() {
        self::$auth = Auth::instance();
    }


    public static function instance () { //声明一个静态公共方法，供外部获取唯一实例
        if (!(self::$userObj instanceof self)) {
            self::$userObj = new self;
        }
        return self::$userObj;
    }

    /**创建用户 和 写入银行卡*/
    public function createData($data) {
        //首先判断下用户是否存在 如果存在就不创建了
        $user = User::get(['identity_card'=> $data['identity_card']]);
        if (!$user) {
            // 检测用户名或邮箱、手机号是否存在
            $ip = request()->ip();
            $time = time();

            $params = [
                'nickname'  => $data['real_name'] ,
                'username'  => $data['identity_card'] ,  //用户名为身份证号码不能修改
                'real_name'  => $data['real_name'] ,
                'identity_card'  => $data['identity_card'],
                'mobile' => $data['mobile'],
                'salt'      => Random::alnum(),
                'jointime'  => $time,
                'joinip'    => $ip,
                'logintime' => $time,
                'loginip'   => $ip,
                'prevtime'  => $time,
                'status'    => 'normal'
            ];
            $params['password'] = self::$auth->getEncryptPassword(Random::alnum(), $params['salt']);
            $user = User::create($params);
        }

        $this->createBank($data, $user);
        return $user;
    }

    /**写入银行卡*/
    public function createBank($data, $user) {
        $d['bank_card'] = $data['bank_card'];
        $d['user_id'] = $user['id'];
        $d['mobile'] = $data['mobile'];
        $d['type'] = $data['type'];

        //查询银行卡是否写入
        $res = Db::name('account_bank')->useSoftDelete('deletetime')->where(['user_id'=>$user['id'], 'bank_card' => $data['bank_card'], 'type'=>$data['type']])->find();
        if ($res) {
            return true;
        }

        $iRes = Db::name('account_bank')->insert($d);
        if (!$iRes) {
            throw new ValidateException('写入银行卡失败');
        }

        return true;
    }

    /**
     * 更新用户信息
     * @param  $identity_card 身份证号码
     * @param object $user 当前登陆用户模型对象
     * @return object
     */
    public function updateUser(User $user) {
        if (!$user->identity_card) {
            throw new ValidateException('信息错误');
        }
        $already = User::get(['identity_card' => $user->identity_card]);
        Db::startTrans();
        try {
            //如果用户已经存在
            if ($already) {
                $already->nickname =  $user->nickname;
                $already->avatar =  $user->avatar;
                $already->gender =   $user->gender;
                $already->identity_card_front = $user->identity_card_front;
                $already->identity_card_back =  $user->identity_card_back;
                $already->real_name = $user->real_name;
                $already->identity_card = $user->identity_card;
                $already->username = $user->username;
                Db::name('third')->where('user_id', $user['id'])->setField('user_id', $already['id']);
                //删除以前用户
                if ($user['id'] != $already['id']) {
                    $user->delete();
                }
            } else {
                $already = $user;
            }
            //后台为录入 直接把改用户作为 正式用户
            $already->save();
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            throw new ValidateException($e->getMessage());
        }
        return $already;
    }


    /**
     * 用户信息
     */
    public function userInfo() {
        $field = ['id', 'username', 'nickname', 'mobile', 'avatar', 'score','is_renzheng', 'real_name', 'identity_card','identity_card_front', 'identity_card_back'];
        $auth = self::$auth->instance();
        $user = $auth->getUser();
        $user = $user->visible($field)->toArray();
        $_token = $auth->getToken();
        $token = Token::get($_token);
        $userinfo = array_merge($user, $token);

        //配置信息 一起返回
        $userinfo['concat_phone'] = config('site.concat_phone');
        return $userinfo;
    }
    private function __clone() {} //声明私有的克隆方法，防止对象被克隆

    public function __sleep() { //重写__sleep方法，将返回置空，防止序列化反序列化获得新的对象
        return [];
    }

}